<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>基金历史净值爬取</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .container { max-width: 800px; }
        input, button { padding: 10px; margin: 10px 0; font-size: 16px; }
        button { background: #007bff; color: white; border: none; cursor: pointer; }
        button:hover { background: #0056b3; }
        .result { margin-top: 20px; padding: 15px; border: 1px solid #ddd; background: #f8f9fa; }
        .error { color: red; }
        .success { color: green; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .pagination { list-style: none; display: flex; gap: 5px; }
        .pagination li { display: inline; }
        .pagination a { padding: 5px 10px; text-decoration: none; border: 1px solid #ccc; }
        .pagination .disabled a { color: #ccc; pointer-events: none; }
    </style>
</head>
<body>
<div class="container">

    <!-- 查询表单 -->
    <form onsubmit="query(event)">
        <div class="form-group">
            <label>基金代码:</label>
            <input type="text" id="fundCode" required />
        </div>
        <button type="submit">查询净值</button>
        <a href="/" class="btn">index页</a>
    </form>

    <!-- 数据表格 -->
    <table id="navTable" style="display: none;">
        <thead>
        <tr>
            <th>代码</th><th>名称</th><th>日期</th><th>单位净值</th><th>累计净值</th><th>日增长</th>
        </tr>
        </thead>
        <tbody id="navBody"></tbody>
    </table>

    <!-- 分页 -->
    <div id="pagination" style="margin-top: 20px; display: none;">
        <ul class="pagination" id="paginationList"></ul>
    </div>

    <!-- 导出按钮 -->
    <div id="exportLinks" style="margin-top: 20px; display: none;">
        <a href="#" id="exportExcel" class="btn btn-success">📥 导出 Excel</a>
        <a href="#" id="exportCsv" class="btn btn-info">📤 导出 CSV</a>
    </div>

    <!-- 净值趋势图 -->
    <div class="card mt-4" id="chartContainer" style="display: none;">
        <div class="card-header"><h5>📈 净值趋势图</h5></div>
        <div class="card-body">
            <div id="navChart" style="height: 400px; width: 100%;"></div>
        </div>
    </div>

</div>

<!-- 引入 ECharts -->
<script src="/js/echarts.min.js"></script>

<script>
    let currentPage = 0;
    let currentSize = 10;
    let currentFundCode = '';

    // 查询基金净值
    function query(e) {
        e.preventDefault();
        currentFundCode = document.getElementById('fundCode').value.trim();
        if (!/^\d{6}$/.test(currentFundCode)) {
            alert('请输入正确的6位基金代码');
            return;
        }
        currentPage = 0;
        loadNavs();
        loadChart();
        setupExportLinks();
    }

    // 加载净值数据
    function loadNavs(page = currentPage) {
        fetch(`/api/fund/navs?fundCode=${currentFundCode}&page=${page}&size=${currentSize}`)
            .then(res => res.json())
            .then(data => {
                const tbody = document.getElementById('navBody');
                tbody.innerHTML = '';
                data.content.forEach(nav => {
                    const tr = `
                        <tr>
                            <td>${nav.fundCode}</td>
                            <td>${nav.fundName}</td>
                            <td>${nav.date}</td>
                            <td>${nav.unitNav}</td>
                            <td>${nav.accumulatedNav}</td>
                            <td>${nav.dailyGrowth}</td>
                        </tr>`;
                    tbody.innerHTML += tr;
                });

                document.getElementById('navTable').style.display = 'table';
                renderPagination(data, page);
                document.getElementById('exportLinks').style.display = 'block';
            });
    }

    // 渲染分页
    function renderPagination(data, page) {
        const ul = document.getElementById('paginationList');
        ul.innerHTML = '';

        // 上一页
        const prevLi = document.createElement('li');
        prevLi.className = page === 0 ? 'disabled' : '';
        const prevA = document.createElement('a');
        prevA.textContent = '上一页';
        if (page > 0) prevA.onclick = () => loadNavs(page - 1);
        prevLi.appendChild(prevA);
        ul.appendChild(prevLi);

        // 下一页
        const nextLi = document.createElement('li');
        nextLi.className = page >= data.totalPages - 1 ? 'disabled' : '';
        const nextA = document.createElement('a');
        nextA.textContent = '下一页';
        if (page < data.totalPages - 1) nextA.onclick = () => loadNavs(page + 1);
        nextLi.appendChild(nextA);
        ul.appendChild(nextLi);

        document.getElementById('pagination').style.display = 'block';
    }

    // 加载净值趋势图
    function loadChart() {
        const container = document.getElementById('chartContainer');
        container.style.display = 'block';

        // 等待 DOM 更新
        setTimeout(() => {
            const chartDom = document.getElementById('navChart');
            if (!chartDom) {
                console.error('图表容器未找到');
                return;
            }

            const myChart = echarts.init(chartDom);

            fetch(`/api/fund/nav-trend?fundCode=${currentFundCode}`)
                .then(res => res.json())
                .then(data => {
                    if (!data.dates?.length) {
                        chartDom.innerHTML = '暂无数据';
                        return;
                    }
                    const option = {
                        tooltip: { trigger: 'axis' },
                        xAxis: { type: 'category', data: data.dates },
                        yAxis: { type: 'value' },
                        series: [{
                            name: '单位净值',
                            type: 'line',
                            data: data.unitNav,
                            smooth: true,
                            areaStyle: { opacity: 0.2 }
                        }]
                    };
                    myChart.setOption(option);

                    // 自适应窗口大小
                    window.addEventListener('resize', () => myChart.resize());
                })
                .catch(err => {
                    chartDom.innerHTML = '图表加载失败: ' + err.message;
                });
        }, 100);
    }

    // 设置导出链接
    function setupExportLinks() {
        const excelLink = document.getElementById('exportExcel');
        const csvLink = document.getElementById('exportCsv');
        excelLink.href = `/api/export/excel?fundCode=${currentFundCode}`;
        csvLink.href = `/api/export/csv?fundCode=${currentFundCode}`;
    }
</script>
</body>
</html>
